<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${dataId ? '编辑' : '新增'}-物料`"
		width="800px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		append-to-body
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px" :show-message="false">
			<el-row>
				<el-col :span="24">
					<el-form-item class="margin-bottom-10" label="物料分类" prop="categoryIds">
						<div v-if="ruleForm.id" class="flex-start-center width-100-percent">
							<materialCategory
								v-if="isEdit"
								:value="ruleForm.categoryIds"
								:tree-data="treeData"
								:load-node="loadNode"
								@change="onCategoryChange"
							></materialCategory>
							<el-input v-else v-model="ruleForm.categoryName" disabled placeholder="物料分类" />
							<el-checkbox v-model="isEdit" border icon="el-icon-edit" style="margin-left: 2px;">编辑</el-checkbox>
						</div>
						<materialCategory
							v-else
							:value="ruleForm.categoryIds"
							:tree-data="treeData"
							:load-node="loadNode"
							@change="onCategoryChange"
						></materialCategory>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="编码">
						<el-input v-model="ruleForm.code" disabled placeholder="系统自动生成" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="名称" prop="name">
						<el-input v-model="ruleForm.name" placeholder="名称" @blur="onBlurOfNameOrderModels" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="规格型号" prop="models">
						<el-input v-model="ruleForm.models" placeholder="规格型号" @blur="onBlurOfNameOrderModels" />
					</el-form-item>
				</el-col>
				<!--<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="条码">
						<el-input v-model="ruleForm.barCode" placeholder="条码" />
					</el-form-item>
				</el-col>-->
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="计量单位" prop="unitId">
						<el-select v-model="ruleForm.unitId" placeholder="计量单位" class="width-100-percent">
							<el-option v-for="item in unitList" :key="item.id" :label="item.name" :value="item.id" />
						</el-select>
					</el-form-item>
				</el-col>
				<!--<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="辅助计量单位">
						<el-select v-model="ruleForm.secUnitId" placeholder="纱线用途" class="width-100-percent">
							<el-option v-for="item in secUnitList" :key="item.id" :label="item.name" :value="item.id" />
						</el-select>
					</el-form-item>
				</el-col>-->
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="存货类型">
						<div class="read-only-2">{{ ruleForm.typeName }}</div>
					</el-form-item>
				</el-col>
				<!--<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="是否生产">
						<el-radio-group v-model="ruleForm.ifProduction">
							<el-radio :label="true">是</el-radio>
							<el-radio :label="false">否</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="是否启用批号">
						<el-radio-group v-model="ruleForm.enableBatch">
							<el-radio :label="true">是</el-radio>
							<el-radio :label="false">否</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>-->
			</el-row>
			<jk-divider-card title="物料参数" placement="center" class="margin-top-10">
				<el-row>
					<el-col :span="12">
						<el-form-item class="margin-bottom-10" label="支数">
							<jk-number-input v-model="ruleForm.yarnCount" placeholder="支数" @change="calGmByYarnCount" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item class="margin-bottom-10" label="定量(g/m)">
							<div class="flex-start">
								<div class="read-only-2">{{ ruleForm.gramWeight }}</div>
								<span style="margin: 0 5px;">/</span>
								<div class="read-only-2">{{ ruleForm.meters }}</div>
							</div>
						</el-form-item>
					</el-col>
					<!--<el-col :span="12">
						<el-form-item class="margin-bottom-10" label="默认生产区域">
							<el-select v-model="ruleForm.workshopId" placeholder="默认生产区域" class="width-100-percent">
								<el-option v-for="item in workshopList" :key="item.id" :label="item.name" :value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>-->
					<el-col :span="12">
						<el-form-item class="margin-bottom-10" label="工序">
							<el-select v-model="ruleForm.processId" placeholder="工序" class="width-100-percent">
								<el-option v-for="item in processList" :key="item.id" :label="item.name" :value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<!--<el-col :span="12">
						<el-form-item class="margin-bottom-10" label="默认工艺路线">
							<el-select v-model="ruleForm.specPathId" placeholder="默认工艺路线" class="width-100-percent">
								<el-option v-for="item in pathList" :key="item.id" :label="item.name" :value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>-->
					<el-col :span="12">
						<el-form-item class="margin-bottom-10" label="纺纱方式">
							<el-select v-model="ruleForm.spinTypeId" placeholder="纺纱方式" class="width-100-percent">
								<el-option v-for="item in spinTypeList" :key="item.id" :label="item.name" :value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<!--<el-col :span="12">
						<el-form-item class="margin-bottom-10" label="纺纱工艺">
							<el-select v-model="ruleForm.technologyId" placeholder="纺纱工艺" class="width-100-percent">
								<el-option v-for="item in fsgyList" :key="item.id" :label="item.name" :value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>-->
					<el-col :span="12">
						<el-form-item class="margin-bottom-10" label="纱线用途">
							<el-select v-model="ruleForm.purposeId" placeholder="纱线用途" class="width-100-percent">
								<el-option v-for="item in sxytList" :key="item.id" :label="item.name" :value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item class="margin-bottom-10" label="原料成分">
							<el-select v-model="ruleForm.componentId" placeholder="原料成分" class="width-100-percent">
								<el-option v-for="item in ylcfList" :key="item.id" :label="item.name" :value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<!--<el-col :span="12">
						<el-form-item class="margin-bottom-10" label="加工费">
							<jk-number-input v-model="ruleForm.yarnCount" placeholder="加工费" />
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item class="margin-bottom-10" label="供应商">
							<jk-input v-model="ruleForm.supplier" placeholder="供应商" />
						</el-form-item>
					</el-col>-->
				</el-row>
			</jk-divider-card>
		</el-form>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import {
        spinProductCreate,
        spinProductUpdate,
        spinProductGet
    } from '../../../api/material/material';
    import { clearBlankSpace, createTree, getFamily } from '../../../utils/jk/jk-tool';
    import { validateArr } from '../../../utils/jk/validator';
    import { spinProductCategoryList } from '../../../api/material/category';
    import { spinProductPropertyPage } from '../../../api/material/property';
    import { spinUnitPage } from '../../../api/basicData/unit';
    import { spinProcessPage } from '../../../api/technology/process';
    import { systemBusinessDictPage } from '../../../api/basicData/businessDict';
    import materialCategory from './components/material-category';
    import { mathJsDiv } from '../../../utils/jk/jk-cals';
    export default {
        name: 'Material',
        props: {
            // 页面权限的前缀
            permissionPrefix: {
                type: String,
                default: ''
            },
            selectTreeItem: {
                type: Object,
                default() {
                    return {};
                }
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        components: {
            materialCategory
        },
        mixins: [calHeight],
        data() {
            return {
                isEdit: false,
                spinTypeList: [],
                secUnitList: [],
                unitList: [],
                fsgyList: [],
                sxytList: [],
                ylcfList: [],
                pathList: [],
                rawData: [],
                treeData: [],
                processList: [],
                saveBtnLoading: false,
                workshopList: [],
                showDialog: false,
                showLoading: true,
                confirmBtnLoading: false,
                saveDialogState: false,
                ruleForm: {
                    id: null,
                    code: '',
                    name: null,
                    auditState: 1,
                    processId: null,
                    processCode: null,
                    processName: null,
                    supplier: '',
                    models: '',
                    barCode: '',
                    categoryIds: [],
                    categoryId: [],
                    categoryCode: '',
                    categoryName: '',
                    componentId: null,
                    componentCode: '',
                    componentName: '',
                    purposeId: null,
                    purposeCode: '',
                    purposeName: '',
                    specPathId: null,
                    specPathCode: '',
                    specPathName: '',
                    technologyId: null,
                    technologyCode: '',
                    technologyName: '',
                    workshopId: null,
                    workshopCode: '',
                    workshopName: '',
                    unitId: null,
                    unitCode: '',
                    unitName: '',
                    secUnitId: null,
                    secUnitCode: '',
                    secUnitName: '',
                    enableBatch: false,
                    ifProduction: false,
                    yarnCount: null,
                    typeId: null,
                    typeName: ''
                },
                rules: {
                    categoryIds: [{ required: true, validator: validateArr, trigger: 'change' }],
                    categoryName: [{ required: true, trigger: 'change' }],
                    typeId: [{ required: true, trigger: 'change' }],
                    models: [{ required: true, trigger: 'change' }],
                    unitId: [{ required: true, trigger: 'change' }],
                    name: [{ required: true, trigger: 'change' }]
                }
            };
        },
        methods: {
            // 根据"支数"计算定量
            calGmByYarnCount() {
                if (this.ruleForm.yarnCount) {
                    // 克重(保留两位小数并四舍五入) = 583.1 / 支数
                    let val = mathJsDiv(583.1, this.ruleForm.yarnCount);
                    val = Number(val.toFixed(2));

                    this.$set(this.ruleForm, 'gramWeight', val);
                    this.$set(this.ruleForm, 'meters', 1000);
                } else {
                    this.$set(this.ruleForm, 'gramWeight', 0);
                    this.$set(this.ruleForm, 'meters', 0);
                }
            },
            onCategoryChange(e) {
                if (e) {
                    const item = this.rawData.find(x => x.id === e[e.length - 1]) || {};
                    this.$set(this.ruleForm, 'categoryIds', e);
                    this.$set(this.ruleForm, 'categoryName', item.name);
                    this.$set(this.ruleForm, 'typeId', item.typeId);
                    this.$set(this.ruleForm, 'typeCode', item.typeCode);
                    this.$set(this.ruleForm, 'typeName', item.typeName);
                } else {
                    this.$set(this.ruleForm, 'typeId', null);
                    this.$set(this.ruleForm, 'typeCode', '');
                    this.$set(this.ruleForm, 'typeName', '');
                }
            },
            loadNode(node, resolve) {
                if (node.level === 0) {
                    return resolve([{ name: 'region' }]);
                }
                const params = {
                    parentId: node.data.id
                };
                return spinProductCategoryList(params).then(res => {
                    if (res.data.status === 200) {
                        const list = res.data.res ? res.data.res.map(x => {
                            x.nameAndCode = `${x.code} ${x.name}`;
                            x.leaf = false;
                            return x;
                        }) : [];
                        this.rawData.push(...list);
                        resolve(list);
                    }
                });
            },
            onBlurOfNameOrderModels() {
                this.$set(this.ruleForm, 'name', clearBlankSpace(this.ruleForm.name));
                this.$set(this.ruleForm, 'models', clearBlankSpace(this.ruleForm.models));
            },
            getParamData() {
                this.$set(this.ruleForm, 'models', clearBlankSpace(this.ruleForm.models));
                this.$set(this.ruleForm, 'name', clearBlankSpace(this.ruleForm.name));
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                if (!this.dataId) delete params.id;
                // 工序
                const processItem = this.processList.find(x => x.id === params.processId) || { code: '', name: '' };
                params.processCode = processItem.code;
                params.processName = processItem.name;
                // 物料分类
                params.categoryId = params.categoryIds[params.categoryIds.length - 1];
                if (params.categoryId && this.rawData.some(x => x.id === params.categoryId)) {
                    const categoryItem = this.rawData.find(x => x.id === params.categoryId) || { code: '', name: '', typeId: '', typeCode: '', typeName: '' };
                    params.categoryCode = categoryItem.code;
                    params.categoryName = categoryItem.name;
                    // 存货类型
                    params.typeId = categoryItem.typeId;
                    params.typeCode = categoryItem.typeCode;
                    params.typeName = categoryItem.typeName;
                }
                delete params.categoryIds;
                // 基准计量单位
                const unitItem = this.unitList.find(x => x.id === params.unitId) || { code: '', name: '' };
                params.unitCode = unitItem.code;
                params.unitName = unitItem.name;
                // 区域
                const workshopItem = this.workshopList.find(x => x.id === params.workshopId) || { code: '', name: '' };
                params.workshopCode = workshopItem.code;
                params.workshopName = workshopItem.name;
                // 工艺路线
                const pathItem = this.pathList.find(x => x.id === params.specPathId) || { code: '', name: '' };
                params.specPathCode = pathItem.code;
                params.specPathName = pathItem.name;
                // 纺纱工艺
                const technologyItem = this.fsgyList.find(x => x.id === params.technologyId) || { code: '', name: '' };
                params.technologyCode = technologyItem.code;
                params.technologyName = technologyItem.name;
                // 纱线用途
                const sxytItem = this.sxytList.find(x => x.id === params.purposeId) || { code: '', name: '' };
                params.purposeCode = sxytItem.code;
                params.purposeName = sxytItem.name;
                // 原料成分
                const ylcfItem = this.ylcfList.find(x => x.id === params.componentId) || { code: '', name: '' };
                params.componentCode = ylcfItem.code;
                params.componentName = ylcfItem.name;
                // 辅助计量单位
                const secUnitItem = this.secUnitList.find(x => x.id === params.secUnitId) || { code: '', name: '' };
                params.secUnitCode = secUnitItem.code;
                params.secUnitName = secUnitItem.name;
                // 纺纱方式
                const spinTypeItem = this.spinTypeList.find(x => x.id === params.spinTypeId) || { code: '', name: '' };
                params.spinTypeCode = spinTypeItem.code;
                params.spinTypeName = spinTypeItem.name;
                return params;
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            createAndUpdateRequest() {
                this.saveBtnLoading = true;
                const api = !this.dataId ? spinProductCreate : spinProductUpdate;
                api(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish', res.data.res);
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return spinProductGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        resData.categoryIds = resData.categoryId ? [resData.categoryId] : [];
                        this.ruleForm = res.data.res;
                    }
                });
            },
            getTreeListRequest() {
                return spinProductCategoryList({
                    parentId: 0
                }).then(res => {
                    if (res.data.status === 200) {
                        this.rawData = res.data.res.map(x => x);
                        const list = res.data.res ? res.data.res.map(x => {
                            x.nameAndCode = `${x.code} ${x.name}`;
                            return x;
                        }) : [];
                        this.treeData = createTree(list, {});
                    }
                });
            },
            getSxytListRequest() {
                return spinProductPropertyPage({
                    typeCode: 'SXYT'
                }).then(res => {
                    if (res.data.status === 200) {
                        this.sxytList = res.data.res;
                    }
                });
            },
            getFsgyListRequest() {
                return spinProductPropertyPage({
                    typeCode: 'FSGY'
                }).then(res => {
                    if (res.data.status === 200) {
                        this.fsgyList = res.data.res;
                    }
                });
            },
            getYlcfListRequest() {
                return spinProductPropertyPage({
                    typeCode: 'YLCF'
                }).then(res => {
                    if (res.data.status === 200) {
                        this.ylcfList = res.data.res;
                    }
                });
            },
            getUnitListRequest() {
                return spinUnitPage({ auditState: 1 }).then(res => {
                    if (res.data.status === 200) {
                        this.unitList = res.data.res;
                        if (!this.dataId) {
                            res.data.res.forEach(x => {
                                if (x.name === '千克') {
                                    this.$set(this.ruleForm, 'unitId', x.id);
                                    this.$set(this.ruleForm, 'unitCode', x.code);
                                    this.$set(this.ruleForm, 'unitName', x.name);
                                }
                            });
                        }
                        this.secUnitList = res.data.res;
                    }
                });
            },
            getProcessListRequest() {
                return spinProcessPage({ workshopId: this.ruleForm.workshopId }).then(res => {
                    if (res.data.status === 200) {
                        this.processList = res.data.res;
                    }
                });
            },
            getSpinTypeListRequest() {
                return systemBusinessDictPage({ categoryCode: 'SPIN_TYPE' }).then(res => {
                    if (res.data.status === 200) {
                        this.spinTypeList = res.data.res || [];
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                await this.getSpinTypeListRequest();
                await this.getUnitListRequest();
                await this.getSxytListRequest();
                // await this.getFsgyListRequest();
                await this.getYlcfListRequest();
                await this.getTreeListRequest();
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                if (!this.dataId) {
                    this.$set(this.ruleForm, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                    this.$set(this.ruleForm, 'workshopCode', this.$store.state.user.userWorkshop.defaultWorkshopCode);
                    this.$set(this.ruleForm, 'workshopName', this.$store.state.user.userWorkshop.defaultWorkshopName);
                }
                await this.getProcessListRequest();
                if (this.dataId) await this.getDetailRequest();
                if (!this.dataId) {
                    // this.$set(this.ruleForm, 'categoryIds', [this.selectTreeItem.id]);
                    this.$set(this.ruleForm, 'categoryId', this.selectTreeItem.id);
                    this.$set(this.ruleForm, 'categoryCode', this.selectTreeItem.code);
                    this.$set(this.ruleForm, 'categoryName', this.selectTreeItem.name);
                    this.$set(this.ruleForm, 'typeId', this.selectTreeItem.typeId);
                    this.$set(this.ruleForm, 'typeName', this.selectTreeItem.typeName);
                }
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
